<template>
  <div class="app-container">
    <el-button type="primary" plain @click="add()">新增车辆</el-button>
    <el-button type="primary" plain @click="buyPark()">购买停车位</el-button>
    <div style="float: right;">
      <el-button type="primary" plain @click="startPark()">开始停车</el-button>
      <el-button type="primary" plain @click="endPark()">结束停车</el-button>

      <el-popover placement="right" width="330" trigger="click">
        <el-table :data="tableData">
          <el-table-column width="150" property="owner" label="业主">

          </el-table-column>
          <el-table-column width="150" property="fee" label="收费">

          </el-table-column>
        </el-table>
        <el-button slot="reference">停车收费规则</el-button>
      </el-popover>
    </div>


    <el-table :data="list" border fit highlight-current-row style="width: 100%">

      <!--  <el-table-column width="100px" align="center" label="车辆ID">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="车牌号">
        <template slot-scope="scope">
          <span>{{ scope.row.carNumber }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="品牌">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="车辆颜色">
        <template slot-scope="scope">
          <span>{{ scope.row.color }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="车辆创建时间">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>&nbsp;
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="车辆更新时间">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>&nbsp;
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="update(scope.row)" circle title="修改车位">
          </el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="delInfo(scope.row)" circle title="删除车位">
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 新增车辆对话框 -->
    <el-dialog :title="title" :visible.sync="isShow" width="30%">
      <el-form ref="form" label-width="100px">
        <el-form-item label="车辆品牌">
          <el-col :span="22">
            <input type="hidden" v-model="carForm.id" />
            <el-input placeholder="请输入车辆品牌" v-model="carForm.remark"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="车牌号码">
          <el-col :span="22">
            <el-input placeholder="请输入车牌号码" v-model="carForm.carNumber"></el-input>
          </el-col>
        </el-form-item>


        <el-form-item label="车辆颜色">
          <el-col :span="22">
            <el-input placeholder="请输入车辆颜色" v-model="carForm.color"></el-input>
          </el-col>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="saveInfo">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 业主购买车位对话框 -->
    <el-dialog :title="title" :visible.sync="isShowPark" width="30%">
      <el-form ref="form" label-width="100px">
        <el-form-item label="购买车位日期">
          <el-col :span="22">
            <!-- <input type="hidden" v-model="carForm.id" /> -->
            <div class="block">
              <el-date-picker v-model="parkingForm.createTime" type="datetime" placeholder="选择日期时间" align="right"
                :picker-options="pickerOptions" value-format="yyyy-MM-ddTHH:mm:ss">
              </el-date-picker>
            </div>
          </el-col>
        </el-form-item>

        <el-form-item label="购买年限">
          <el-col :span="22">
            <el-select v-model="parkingForm.useType" class="el-dropdown-link">
              <el-option value="1">1年</el-option>
              <el-option value="2">2年</el-option>
              <el-option value="3">3年</el-option>
              <el-option value="4">4年</el-option>
              <el-option value="5">5年</el-option>
              <el-option value="6">6年</el-option>
              <el-option value="7">7年</el-option>
              <el-option value="8">8年</el-option>
              <el-option value="9">9年</el-option>
              <el-option value="10">10年</el-option>
              <el-option value="20">20年</el-option>
            </el-select>
          </el-col>
        </el-form-item>

        <el-form-item label="可购买的车位">
          <el-col :span="22">
            <el-select v-model="parkingForm.code" placeholder="请选择要购买的车位编号">
              <el-option v-for="item in listPark " :value="item.code"></el-option>
            </el-select>
          </el-col>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowPark = false">取 消</el-button>
        <el-button type="primary" @click="buy">购 买</el-button>
      </span>

      <el-popover :span="16" placement="right" title="购买说明" width="200" trigger="click" content="停车位每人限购一个,每年需支付5000元。">
        <el-button slot="reference">购买说明</el-button>
      </el-popover>

    </el-dialog>

    <!-- 支付弹窗(购买停车位) -->
    <el-dialog title="扫描支付" :visible.sync="isShowPay">
      <div id="code" style="width:200px ; height: 200px;"></div>
    </el-dialog>

    <!-- 开始停车对话框 -->
    <el-dialog :title="title" :visible.sync="isShow2" width="30%">
      <el-form ref="form" label-width="100px">
        <el-form-item label="车牌号码">
          <el-col :span="22">
            <input type="hidden" v-model="carForm.id" />
            <el-input placeholder="请输入车牌号码" v-model="parkingForm.carNumber"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow2 = false">取 消</el-button>
        <el-button type="primary" @click="saveInfo2">{{ title }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import myUtil from '../../../utils/myUtil'

  export default {
    name: 'carList',
    data() {
      return {
        list: [],
        listPark: [], // 用于存放从后台获取的可以被购买的公有车位的数据
        title: "新增车辆",
        carForm: {
          id: null,
          //备注：这里默认使用的是业主Id为1的用户，因为登录功能还没实现
          ownerId: 2, //车辆所属成员
          color: "", //车辆颜色
          carNumber: "", //车牌号
          remark: "", //备注（品牌）
          createTime: "", //车辆创建时间
          updateTime: "", //车辆更新时间
        },
        parkingForm: {
          id: null,
          useType: "", //购买停车位使用年限
          code: "", //购买的车位是哪一个
          createTime: "", //车位购买时间
          updateTime: "", //车位购买到期时间
          ownerName: "", //车辆所有人姓名
          ownerId: "", //车辆所有人ID
          telephone: "", //联系方式
          communityId: "", //所在小区ID
        },
        isShow: false, //业主新增车辆对话框
        isShowPark: false, //业主购买车位对话框
        isShowPay: false, //支付弹窗(购买停车位)
        isShow2: false, //用于开始or修改停车模态框的显示
        listLoading: true,
        //用于购买停车位的购买时间
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        tableData: [{
          owner: '购买停车位的业主',
          fee: '无需支付额外的停车费用'
        }, {
          owner: '未购买停车位的业主',
          fee: '每小时一元，不足一小时按一小时计算'
        }]
      }

    },
    methods: {
      //查询分页数据展示到页面，挂载到mouted中
      // carForm.ownerId=1;
      loaddata() {
        var self = this;
        this.axios({
          methods: 'get',
          url: myUtil.url + '/tb-car/cars/' + self.carForm.ownerId,
        }).then(function(rs) {
          console.log(rs);
          self.list = rs.data;
        });
      },
      //加载业主用户的数据（用于购买车位的信息输入（后台传入））
      initOwner() {
        var self = this;
        this.axios({
          methods: 'get',
          url: myUtil.url + '/tb-owner/findById',
          params: {
            id: 2
          }
        }).then(function(rs) {
          console.log(rs.data.info);
          self.parkingForm.telephone = rs.data.info.telephone;
          self.parkingForm.ownerName = rs.data.info.name;
          self.parkingForm.ownerId = rs.data.info.id;
          self.parkingForm.communityId = rs.data.info.communityId;
        });
      },
      //打开新增车位模态框
      add() {
        //显示模态框的标题
        this.title = "新增车辆";
        //显示vue的模态框
        this.isShow = true;
        //清除表单元素，防止之前的数据显示
        this.carForm.id = null;
        this.carForm.carNumber = "";
        this.carForm.color = "";
        this.carForm.remark = "";
        this.carForm.createTime = "";
        this.carForm.updateTime = "";
      },
      //打开修改车位模态框
      update(x) {
        //显示模态框的标题
        this.title = "修改车辆";
        //显示vue的模态框
        this.isShow = true;
        //将数据填充到修改模态框中
        this.carForm.id = x.id;
        this.carForm.carNumber = x.carNumber;
        this.carForm.color = x.color;
        this.carForm.remark = x.remark;
        this.carForm.createTime = x.createTime;
        this.carForm.updateTime = x.updateTime;
      },
      //保存操作
      saveInfo() { //保存
        var url = "";
        var method = "";
        if (this.title == "修改车辆") {
          url = myUtil.url + "/tb-car/updateCar";
          method = "put";
        } else {
          url = myUtil.url + "/tb-car/insertCar";
          method = "post";
        }
        var self = this;
        //利用vue的axios发送ajax请求
        this.axios({
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          method: method,
          url: url,
          data: JSON.stringify(self.carForm),
        }).then(function(rs) {
          console.log(rs.data);
          if (rs.data.info == "保存成功") {
            self.$message({
              message: '车辆保存成功',
              type: 'success'
            });
            // 关闭模态框
            self.isShow = false;
            // 刷新
            self.loaddata();
          }
        })
      },
      delInfo(x) {
        var self = this;
        this.$confirm("你确定要删除车牌号为[" + x.carNumber + "]的车吗?", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.axios({
            method: 'delete',
            url: myUtil.url + '/tb-car/deleteCar/' + x.id,
          }).then(function(rs) {
            console.log(rs.data.info);
            if (rs.data.info == "删除成功") {
              self.$message({
                type: 'success',
                message: '删除成功!'
              });
              //刷新
              self.loaddata();
            }
          });

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //显示购买车位的模态框
      buyPark() {
        //显示模态框的标题
        this.title = "购买停车位";
        //显示vue的模态框
        this.isShowPark = true;
        //将数据填充到修改模态框中
        this.parkingForm.useType = "";
        this.parkingForm.createTime = "";
        this.parkingForm.code = "";
        //利用vue的axios发送ajax请求，获取后台为公有车位的数据
        var self = this;
        this.axios({
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          method: 'get',
          url: myUtil.url + '/tb-parking/codes',
        }).then(function(rs) {
          console.log(rs.data.info);
          self.listPark = rs.data.info;
        })
      },
      //购买停车位
      buy() {
        var mythis = this;
        if (this.parkingForm.code == "" || this.parkingForm.createTime == "" || this.parkingForm.useType == "") {
          this.$message({
            showClose: true,
            message: '请填写完整信息',
            type: 'warning'
          });
          return false;
        }
        //清空二维码
        if (document.getElementById("code")) {
          document.getElementById("code").innerHTML = "";
        }
        //显示弹窗
        this.isShowPay = true;
        $.ajax({
          url: myUtil.url + '/pay/payPark',
          type: "post",
          data: JSON.stringify(mythis.parkingForm),
          contentType: "application/json",
          dataType: "json",
          success: function(data) {
            if (data.url != "error") {
              var qrcode = new QRCode(document.getElementById("code"), {
                width: 200,
                height: 200
              });
              //生成二维码
              qrcode.makeCode(data.url);
              var socket = new WebSocket("ws://" + myUtil.natAppUrl + "/payServer")
              socket.onopen = function() {

              }
              socket.onclose = function() {

              }
              socket.onerror = function() {

              }
              //接收服务端发送的信息
              socket.onmessage = function(data) {
                console.log(data);
                if (data.data == "ok") {
                  //关闭窗口
                  mythis.isShowPay = false;
                  mythis.isShowPark = false;
                  mythis.$message({
                    message: '支付成功',
                    type: 'success'
                  });
                  //业主支付成功后保存数据到TbParkingUse表中，更改TbParking中code为业主选择的数据字段name为私有车位
                  $.ajax({
                    url: myUtil.url + '/tb-parking-use/buyParkUse',
                    type: "post",
                    data: JSON.stringify(mythis.parkingForm),
                    contentType: "application/json",
                    dataType: "json",
                    success: function(data) {
                      if (data.info == "保存成功") {
                        console.log("保存成功");
                      }
                    },
                    error: function() {
                      console.log("添加失败");
                    },
                  })

                } else {
                  mythis.$message.error('支付失败');
                }
              }
            } else {
              mythis.$alert("生成二维码失败");
            }
          }
        })
      },
      //打开开始停车模态框
      startPark() {
        this.title = "开始停车";
        //显示vue的模态框
        this.isShow2 = true;

      },
      //打开结束停车模态框
      endPark() {
        this.title = "结束停车";
        //显示vue的模态框
        this.isShow2 = true;
      },
      //开始停车
      saveInfo2() {
        var mythis = this;
        if (this.parkingForm.carNumber == "") {
          this.$message({
            showClose: true,
            message: '请填写车牌号码',
            type: 'warning'
          });
          return false;
        }
        if (this.title == "开始停车") {
          $.ajax({
            url: myUtil.url + '/tb-parking-use/startPark',
            type: "post",
            data: JSON.stringify(mythis.parkingForm),
            contentType: "application/json",
            dataType: "json",
            success: function(data) {
              if (data.info == "ok") {
                console.log("aaa");
                //成功停车后关闭停车模态框
                mythis.isShow2 = false;
                mythis.$message({
                  message: '停车成功',
                  type: 'success'
                });
              }
            }
          })
        } else {
          var temp = JSON.stringify(mythis.parkingForm);
          //结束停车的提交
          $.ajax({
            url: myUtil.url + '/tb-parking-use/endPark',
            type: "post",
            data: temp,
            contentType: "application/json",
            dataType: "json",
            success: function(data) {
              //针对购买停车位的用户
              if (data.info == "ok1") {
                console.log("aaa");
                //结束停车后关闭停车模态框
                mythis.isShow2 = false;
                mythis.$message({
                  message: '您是购买停车位的用户，无需支付停车费用',
                  type: 'success'
                });
                mythis.$notify({
                  title: '成功',
                  message: '结束停车',
                  type: 'success'
                });
              }
              //针对未购买停车位的用户
              if (data.info == "ok2") {
                console.log("bbb");
                mythis.isShowPay = true; // 打开支付弹窗
                mythis.$message({
                  message: '您未购买停车位,需支付停车费用',
                  type: 'warning'
                });
                //清空二维码
                if (document.getElementById("code")) {
                  document.getElementById("code").innerHTML = "";
                }
                $.ajax({
                  url: myUtil.url + '/pay/payParkingFee',
                  type: "post",
                  data: temp,
                  contentType: "application/json",
                  dataType: "json",
                  success: function(data) {
                    if (data.url != "error") {
                      var qrcode = new QRCode(document.getElementById("code"), {
                        width: 200,
                        height: 200
                      });
                      //生成二维码
                      qrcode.makeCode(data.url);
                      var socket = new WebSocket("ws://" + myUtil.natAppUrl + "/payServer")
                      socket.onopen = function() {

                      }
                      socket.onclose = function() {

                      }
                      socket.onerror = function() {

                      }
                      //接收服务端发送的信息
                      socket.onmessage = function(data) {
                        console.log(data);
                        if (data.data == "ok") {
                          //关闭窗口
                          mythis.isShowPay = false;
                          mythis.isShow2 = false;
                          mythis.$message({
                            message: '支付成功',
                            type: 'success'
                          });
                          //未购买停车位的用户支付成功后，将支付金额和结束停车的时间修改数据
                          $.ajax({
                            url: myUtil.url + '/tb-parking-use/endParkingFee',
                            type: "post",
                            data: temp,
                            contentType: "application/json",
                            dataType: "json",
                            success: function(data) {
                              if (data.info == "保存成功") {
                                console.log("保存成功");
                              }
                            },
                            error: function() {
                              console.log("添加失败");
                            },
                          })

                        } else {
                          mythis.$message.error('支付失败');
                        }
                      }
                    } else {
                      mythis.$alert("生成二维码失败");
                    }
                  }
                })
              }
            }
          })

        }

      },
    },
    mounted() {
      this.loaddata();
      //console.log(this.$route.query.info);
      this.initOwner();
    }
  }
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }

  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
